package com.zues.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 测试文件上传和下载
 */
@Controller
public class FileController {

    /**
     * 文件下载
     * @param session session
     * @return  ResponseEntity
     * @throws IOException
     */
    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext context = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = context.getRealPath("/WEB-INF/static/img/凌华2.jpg");
        //创建输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[fileInputStream.available()];
        //将流读到字节数组中
        fileInputStream.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        // 设置内容类型
        headers.setContentType(MediaType.IMAGE_PNG); // 假设文件是PNG图片
        headers.add("Content-Disposition", "attachment;filename=凌华2.jpg");
        //设置响应状态码
        HttpStatus status = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status);
        //关闭输入流
        fileInputStream.close();
        return responseEntity;
    }

    @RequestMapping("testUp")
    public String testUp(MultipartFile img,HttpSession session) throws IOException {

        String filename = img.getOriginalFilename();
        //处理文件重名问题
        String hzname = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString() + hzname;

        ServletContext context = session.getServletContext();
        String realPath = context.getRealPath("uploadImg");
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdir();
        }

        String finalPath = realPath + File.separator + filename;
        //实现上传功能
        img.transferTo(new File(finalPath));
        return "success";
    }
}
